﻿using System;
using Microsoft.Practices.ObjectBuilder;
using Common;
using System.Web.UI.WebControls;
using System.Collections.Generic;
using System.Linq;
using System.Globalization;

namespace CSC440TeamOne.Admin.Views
{
    public partial class UserManual : Microsoft.Practices.CompositeWeb.Web.UI.Page, IUserManualView
    {
        private UserManualPresenter _presenter;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!this.IsPostBack)
            {
                var tempInt = 0;

                CurrentSectionId = int.TryParse(Request.Params["Index"], out tempInt) ? tempInt : 0;

                this._presenter.OnViewInitialized();
            }
            this._presenter.OnViewLoaded();
        }

        [CreateNew]
        public UserManualPresenter Presenter
        {
            get
            {
                return this._presenter;
            }
            set
            {
                if (value == null)
                    throw new ArgumentNullException("value");

                this._presenter = value;
                this._presenter.View = this;
            }
        }

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            btnAddContent.Click += new EventHandler(btnAddContent_Click);

            btnEdit.Click += new EventHandler(btnEdit_Click);

            btnPreview.Click += new EventHandler(btnPreview_Click);

            btnSave.Click += new EventHandler(btnSave_Click);

            repEditUserManualPages.ItemDataBound += new RepeaterItemEventHandler(repEditUserManualPages_ItemDataBound);

            repPreviewUserManualPages.ItemDataBound += new RepeaterItemEventHandler(repPreviewUserManualPages_ItemDataBound);

            btnAddSection.Click += new EventHandler(btnAddSection_Click);
        }

        void btnAddSection_Click(object sender, EventArgs e)
        {
            _presenter.OnAddSection();
        }

        void repPreviewUserManualPages_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            ControlBinder<RepeaterItem, UserManualContent>.Bind(e.Item, a =>
            {
                var userManaualPage = a.BusinessItem;

                if (!userManaualPage.Deleted)
                {
                    var litTitle = a.Find<Literal>("litTitle");

                    litTitle.Text = userManaualPage.Title;

                    var litContent = a.Find<Literal>("litContent");

                    litContent.Text = userManaualPage.Content;

                    var imgImage = a.Find<Image>("imgImage");

                    imgImage.ImageUrl = userManaualPage.Image;

                    imgImage.AlternateText = userManaualPage.Caption;

                    var litCaption = a.Find<Literal>("litCaption");

                    litCaption.Text = userManaualPage.Caption;
                }
            });
        }

        void repEditUserManualPages_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            ControlBinder<RepeaterItem, UserManualContent>.Bind(e.Item, a =>
           {
               var userManaualPage = a.BusinessItem;

               var hfId = a.Find<HiddenField>("hfId");

               hfId.Value = userManaualPage.Id.ToString(CultureInfo.InvariantCulture);

               var txtTitle = a.Find<TextBox>("txtTitle");

               txtTitle.Text = userManaualPage.Title;

               var txtContent = a.Find<TextBox>("txtContent");

               txtContent.Text = userManaualPage.Content;

               var txtImage = a.Find<TextBox>("txtImage");

               txtImage.Text = userManaualPage.Image;

               var txtCaption = a.Find<TextBox>("txtCaption");

               txtCaption.Text = userManaualPage.Caption;

               var chkDelete = a.Find<CheckBox>("chkDelete");

               chkDelete.Checked = userManaualPage.Deleted;
           });
        }

        void btnSave_Click(object sender, EventArgs e)
        {
            _presenter.OnSave();
        }

        void btnPreview_Click(object sender, EventArgs e)
        {
            _presenter.OnPreview();
        }

        void btnEdit_Click(object sender, EventArgs e)
        {
            mvState.SetActiveView(vwEdit);
        }

        void btnAddContent_Click(object sender, EventArgs e)
        {
            _presenter.OnAddContent();
        }

        public int CurrentSectionId
        {
            get
            {
                var result = 0;

                var viewStateResult = ViewState["CurrentIndex"];

                if (viewStateResult != null)
                {
                    result = Convert.ToInt32(viewStateResult);
                }

                return result;
            }
            set
            {
                ViewState["CurrentIndex"] = value;
            }
        }

        public void Show(UserManualModel model)
        {
            mvState.SetActiveView(vwEdit);

            var userManualSection = model.CurrentUserManualSection;

            txtSectionName.Text = userManualSection.Title;

            UserManualSectionId = userManualSection.Id;

            UserManualSectionParent = userManualSection.Parent;

            IEnumerable<UserManualContent> userManualPages = userManualSection.Content;

            if (userManualPages.Any())
            {
                repEditUserManualPages.DataSource = userManualPages;

                repEditUserManualPages.DataBind();
            }

            var userManualSectionMap = model.UserManualSectionMap;

            if (userManualSectionMap != null)
            {
                RecBuildSideTree(tblSide, userManualSectionMap.Root, CurrentSectionId);
            }
        }

        private static void RecBuildSideTree(Table table, UserManualSection userManualSection, int selectedIndex)
        {
            if (table == null || userManualSection == null)
            {
                return;
            }

            TableRow tableRow = new TableRow();

            TableCell tableCell = new TableCell();

            tableCell.Text = "L";

            tableRow.Cells.Add(tableCell);

            tableCell = new TableCell();

            var link = new HyperLink();

            link.Text = userManualSection.Title;

            link.NavigateUrl = string.Format("UserManual.aspx?Index={0}", userManualSection.Id);

            tableCell.Controls.Add(link);

            if (selectedIndex == userManualSection.Id)
            {
                tableCell.CssClass = "selected";
            }

            tableRow.Cells.Add(tableCell);

            table.Rows.Add(tableRow);

            var children = userManualSection.Children;

            if (children.Any())
            {
                foreach (var child in children)
                {
                    tableRow = new TableRow();

                    tableCell = new TableCell();

                    tableRow.Cells.Add(tableCell);

                    tableCell = new TableCell();

                    Table childTable = new Table();

                    RecBuildSideTree(childTable, child, selectedIndex);

                    tableCell.Controls.Add(childTable);

                    tableRow.Cells.Add(tableCell);

                    table.Rows.Add(tableRow);
                }
            }
        }

        public void Update(UserManualModel model)
        {
            var currentUserManualSection = model.CurrentUserManualSection;

            currentUserManualSection.Parent = UserManualSectionParent;

            currentUserManualSection.Title = txtSectionName.Text;

            foreach (RepeaterItem item in repEditUserManualPages.Items)
            {
                var hfId = item.FindControl("hfId") as HiddenField;

                int intUserManualContentId = 0;

                if (int.TryParse(hfId.Value, out intUserManualContentId))
                {
                    var userManualContent = currentUserManualSection.FindUserManualContentById(intUserManualContentId);

                    if (userManualContent == null)
                    {
                        userManualContent = currentUserManualSection.AddNewContent();
                    }

                    if (userManualContent != null)
                    {
                        var txtTitle = item.FindControl("txtTitle") as TextBox;

                        userManualContent.Title = txtTitle.Text;

                        var txtContent = item.FindControl("txtContent") as TextBox;

                        userManualContent.Content = txtContent.Text;

                        var txtImage = item.FindControl("txtImage") as TextBox;

                        userManualContent.Image = txtImage.Text;

                        var txtCaption = item.FindControl("txtCaption") as TextBox;

                        userManualContent.Caption = txtContent.Text;

                        var chkDelete = item.FindControl("chkDelete") as CheckBox;

                        userManualContent.Deleted = chkDelete.Checked;
                    }
                }
            }
        }

        public void OnSaveCompleted(UserManualModel model)
        {
            Show(model);
        }

        public void OnAddContentCompleted(UserManualModel model)
        {
            Show(model);
        }

        public void OnAddSectionCompleted(UserManualModel model)
        {
            Show(model);
        }

        protected int UserManualSectionId
        {
            get
            {
                var result = 0;

                var viewStateResult = ViewState["UserManualSectionId"];

                if (viewStateResult != null)
                {
                    result = Convert.ToInt32(viewStateResult);
                }

                return result;
            }
            set
            {
                ViewState["UserManualSectionId"] = value;
            }
        }

        protected int UserManualSectionParent
        {
            get
            {
                var result = 0;

                var viewStateResult = ViewState["UserManualSectionParent"];

                if (viewStateResult != null)
                {
                    result = Convert.ToInt32(viewStateResult);
                }

                return result;
            }
            set
            {
                ViewState["UserManualSectionParent"] = value;
            }
        }


        public void OnPreviewCompleted(UserManualModel model)
        {
            mvState.SetActiveView(vwPreview);

            var userManualSection = model.CurrentUserManualSection;

            IEnumerable<UserManualContent> userManualPages = userManualSection.Content;

            if (userManualPages.Any())
            {
                repPreviewUserManualPages.DataSource = userManualPages;

                repPreviewUserManualPages.DataBind();
            }

            var userManualSectionMap = model.UserManualSectionMap;

            if (userManualSectionMap != null)
            {
                RecBuildSideTree(tblSide, userManualSectionMap.Root, CurrentSectionId);
            }
        }
    }
}

